<?php

namespace App\Admin\Controllers;

use App\Miya\Models\Area;
use App\Miya\Models\Info;
use App\Miya\Models\UserView;
use Barryvdh\Debugbar\Storage\FilesystemStorage;
use DebugBar\DebugBar;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class ToolController extends AdminController
{
    /**
     * 清除缓存页面
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function clearPageCache()
    {
        Storage::disk('public_dir')->deleteDirectory('page-cache');
        Cache::forget('clear_data');

        return back()->with(admin_toastr('缓存页面已清除!'));
    }

    /**
     * 清除缓存数据
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function clearCacheData()
    {
        $noteBalance = Cache::get('note.balance');
        Cache::flush();
        Cache::set('note.balance', $noteBalance);

        return back()->with(admin_toastr('缓存数据已清除!'));
    }

    public function clearLogs()
    {
        $files = Storage::disk('log_dir')->allFiles();
        Storage::disk('log_dir')->delete($files);
        Cache::forget('clear_data');

        return back()->with(admin_toastr('系统日志文件已清除!'));
    }

    public function clearViews()
    {
        $files = Storage::disk('view_dir')->allFiles();
        Storage::disk('view_dir')->delete($files);
        Cache::forget('clear_data');

        return back()->with(admin_toastr('页面渲染文件已清除!'));
    }

    public function clearDirtyData()
    {
        Info::doesntHave('classify')->get()->each(function ($model) {
            $model->delete();
        });

        return back()->with(admin_toastr('脏数据(无分类信息)已清除!'));
    }

    public function clearUvRecord()
    {
        $ips = UserView::select(['ip', DB::raw('count(*) as num')])->groupBy('ip')
            ->orderBy('num', 'DESC')->take(100)->get();

        UserView::whereIn('ip', $ips->pluck('ip'))->delete();
        DB::raw('optimize table miya3_user_views;');
        Cache::forget('clear_data');
        return back()->with(admin_toastr('uv记录已优化!'));
    }
}
